package com.jianying.day02;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * ClassName: Flink01_par
 * Package: com.atguigu.day02
 * Description:
 *
 * @Author: tubage
 * @Create: 2024/3/30 10:33
 * @Version: 1.0
 */
public class Flink01_par {
    public static void main(String[] args) throws Exception {
        // TODO 本地WebUI
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
//        Configuration conf = new Configuration();
//        conf.set(RestOptions.PORT, 8081);
//        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(conf);
        DataStreamSource<String> streamSource = env.socketTextStream("hadoop102", 8888);
        // TODO 全局指定并行度
        env.setParallelism(2);

        SingleOutputStreamOperator<String> flatMapDS = streamSource.flatMap(
                new FlatMapFunction<String, String>() {
                    @Override
                    public void flatMap(String s, Collector<String> collector) throws Exception {
                        String[] words = s.split(" ");
                        for (String word : words) {
                            collector.collect(word);
                        }
                    }
                }
        );

        SingleOutputStreamOperator<Tuple2<String, Long>> tupDS = flatMapDS.map(
                new MapFunction<String, Tuple2<String, Long>>() {
                    @Override
                    public Tuple2<String, Long> map(String s) throws Exception {
                        return Tuple2.of(s, 1L);
                    }
                }
        ).setParallelism(5);

        KeyedStream<Tuple2<String, Long>, Tuple> keyByDS = tupDS.keyBy(0);
        SingleOutputStreamOperator<Tuple2<String, Long>> sumDS = keyByDS.sum(1);
        sumDS.print();
        env.execute();
    }
}
